package com.yh.correct.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.yh.common.utils.ExcelUtil;
import com.yh.correct.model.Condition;
import com.yh.correct.model.CorrectedPerson;
import com.yh.correct.model.JudicialDeptment;
import com.yh.correct.model.Page;
import com.yh.correct.model.ResultData;
import com.yh.correct.model.RuleBreak;
import com.yh.correct.service.IRuleBreakService;

/**
 * @author 刘文涛 E-mail: 894516860@qq.com
 * @version 创建时间：2017年3月10日 上午10:21:48 违规违纪记录模型控制器
 */
@RestController
@RequestMapping(value = "/rulebreak")
public class RuleBreakController {
	/**
	 * 日志记录
	 */
	private static Logger logger = LogManager.getLogger(RuleBreakController.class);
	/**
	 * 注入违规违纪服务
	 */
	@Autowired
	private IRuleBreakService rulebreakservice;

	/**
	 * 模糊查询 查询条件(矫正单位,服刑人员,违规日期)
	 * 
	 * @return
	 */
	@RequestMapping(value = "/querylike")
	public Page queryLikeRuleBreak(int pageSize, int pageNum, Condition condition) {
		logger.info("查询违规违纪条件" + condition);
		Map<String, Object> map = new HashMap<String, Object>();
				map.put("pageSize", pageSize);
				map.put("pageNum", pageNum);
				map.put("cunit", condition.getCunit());
				map.put("cname", condition.getCname());
				try {
					if (condition.getCdate() != null && !"".equals(condition.getCdate())) {
						java.util.Date date = new SimpleDateFormat("yyyy-MM-dd").parse(condition.getCdate());
						java.sql.Date cdate = new java.sql.Date(date.getTime());
						map.put("cdate", cdate);
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			Page page = rulebreakservice.getLikeRuleBreak(map);
			return page;
	}

	/**
	 * 获取违规违纪详情
	 * 
	 * @param request
	 * @param rulebreak
	 * @return
	 */
	@RequestMapping(value = "/detail")
	public ModelAndView getDetail(HttpServletRequest request, RuleBreak rulebreak, String sort) {
		Map<String, Object> m = rulebreakservice.getRuleBreakById(rulebreak);
		Map<String, Object> rsMap = new HashMap<String, Object>();
		rsMap.put("details", m);
		logger.info("查看详情" + m.toString());
		if ("check".equals(sort)) {
			return new ModelAndView("examine/rulebreak_check", rsMap);
		}
		return new ModelAndView("examine/rulebreak_edit", rsMap);
	}

	/**
	 * 获取所有矫正单位
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/allunit")
	public ModelAndView getAllUnit(String sort) throws UnsupportedEncodingException {
		List<JudicialDeptment> list = rulebreakservice.getAllUnit();
		Map<String, Object> rsMap = new HashMap<String, Object>();
		rsMap.put("allunit", list);
		if ("rulebreak".equals(sort)) {
			return new ModelAndView("examine/rulebreak_add", rsMap);
		} else if ("monthtest".equals(sort)) {
			return new ModelAndView("examine/monthtest_add", rsMap);
		} else if ("rewordpunish".equals(sort)) {
			return new ModelAndView("examine/rewordpunish_add", rsMap);
		} else if ("bonuspoints".equals(sort)) {
			return new ModelAndView("examine/bonuspoints_add", rsMap);
		} else if ("activist".equals(sort)){
			return new ModelAndView("examine/activist_add", rsMap);
		}  else {
			return new ModelAndView("",rsMap);
		}
	}

	/**
	 * 根据矫正单位id获取矫正人员
	 * 
	 * @param id
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/getAllName")
	public byte[] getAllName(Integer id) throws UnsupportedEncodingException {
		List<CorrectedPerson> list = rulebreakservice.getNameByUid(id);
		String msgs = "";
		for (CorrectedPerson s : list) {
			msgs += "<option value='" + s.getId() + "'>" + s.getName() + "</option>";
		}
		return msgs.getBytes("utf-8");
	}

	/**
	 * 增加违规违纪记录
	 * 
	 * @param rulebreak
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/addRuleBreak")
	public ResultData addRuleBreak(RuleBreak rulebreak, String adddate) throws ParseException {
		java.util.Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse(adddate);
		java.sql.Date date = new java.sql.Date(date1.getTime());
		rulebreak.setDate(date);
		logger.info("增加违规违纪记录" + rulebreak.toString());
		rulebreakservice.addRuleBreak(rulebreak);
		return new ResultData();
	}

	/**
	 * 删除违规违纪记录
	 * 
	 * @param rulebreak
	 * @return
	 */
	@RequestMapping(value = "/delRuleBreak")
	public ResultData delRuleBreak(RuleBreak rulebreak) {
		logger.info("删除违规违纪记录id=" + rulebreak.getId());
		rulebreakservice.delRuleBreak(rulebreak);
		return new ResultData();
	}

	/**
	 * 修改违规违纪记录
	 * 
	 * @param rb
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/updateRuleBreak")
	public ResultData updateRuleBreak(RuleBreak rulebreak, String editdate) throws ParseException {
		java.util.Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse(editdate);
		java.sql.Date date = new java.sql.Date(date1.getTime());
		rulebreak.setDate(date);
		logger.info("修改违规违纪记录id=" + rulebreak.toString());
		rulebreakservice.updateRuleBreak(rulebreak);
		return new ResultData();
	}

	/**
	 * tree点击返回url
	 * 
	 * @return
	 */
	@RequestMapping(value = "/url")
	public ModelAndView getUrl() {
		List<JudicialDeptment> list = rulebreakservice.getAllUnit();
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("allUnit", list);
		return new ModelAndView("examine/rulebreak",rs);
	}

	/**
	 * 根据违规违纪记录id批量删除
	 * 
	 * @param id
	 */
	@RequestMapping(value = "/getDeleteIds")
	public void getDeleteIds(int[] id) {
		RuleBreak rulebreak = new RuleBreak();
		for (int i : id) {
			logger.info("批量删除违规违纪id=" + i);
			rulebreak.setId(i);
			rulebreakservice.delRuleBreak(rulebreak);
		}
	}
	/**
	 * 获取违规日期和次数(柱状图)
	 */
	@RequestMapping(value = "/gettimes")
	public Map<String, Object> getRuleBreakTimes(){
		List<Map<String, Object>> data =rulebreakservice.getRuleBreakTimes();
		List<String> date=new ArrayList<String>();
		List<String> times=new ArrayList<String>();
		SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
		for (Map<String, Object> m : data) {
			date.add(sdf.format(m.get("date")));
			times.add(m.get("times").toString());
		}
		String [] dates={};
		String [] d=date.toArray(dates);
		String [] t=times.toArray(dates);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("date", d);
		map.put("times", t);
		return map;
	}

	/**
	 * 导出Excel
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "exportExcel")
	public String download(int[] id, HttpServletRequest request, HttpServletResponse response) throws IOException {
		String fileName = "违规违纪记录excel文件";
		// 生成选择项的导出list
		List<Map<String, Object>> projects = new ArrayList<Map<String, Object>>();
		if (id != null) {
			RuleBreak rulebreak = new RuleBreak();
			for (int i : id) {
				logger.info("批量导出月度考核id=" + i);
				rulebreak.setId(i);
				Map<String, Object> m = rulebreakservice.getRuleBreakById(rulebreak);
				projects.add(m);
			}
		} else {
			projects = createData();
		}
		// 填充projects数据
		List<Map<String, Object>> list = createExcelRecord(projects);
		String columnNames[] = { "序号", "矫正单位", "矫正人员", "违规日期", "违规事实", "处理情况", "备注" };// 列名
		String keys[] = { "id", "jname", "cname", "date", "fact", "solution", "remark" };// map中的key
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		// 设置response参数，可以打开下载页面
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			// Simple read/write loop.
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
		return null;
	}

	private List<Map<String, Object>> createData() {
		// TODO Auto-generated method stub
		// List<Project> list=new ArrayList<Project>();
		List<Map<String, Object>> list = rulebreakservice.getAllRuleBreak();
		return list;
	}

	private List<Map<String, Object>> createExcelRecord(List<Map<String, Object>> projects) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "sheet1");
		listmap.add(map);
		Map<String, Object> object = null;
		for (int j = 0; j < projects.size(); j++) {
			object = projects.get(j);
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("id", object.get("id"));
			mapValue.put("jname", object.get("jname"));
			mapValue.put("cname", object.get("cname"));
			mapValue.put("date", object.get("date"));
			mapValue.put("fact", object.get("fact"));
			mapValue.put("solution", object.get("solution"));
			mapValue.put("remark", object.get("remark"));
			listmap.add(mapValue);
		}
		return listmap;
	}

}
